package com.allwees.core.common.util.csv;

import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author Daniel
 * @Version 1.0.0
 * @Description
 * @CreateTime 2020/8/18 11:01
 */
@SuppressWarnings("rawtypes")
public class CsvUtil {
    /**
     * 从一个流中读取csv文件并序列化为clazz对象
     * @param inputStream
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> readByColumnPosition(InputStream inputStream, Class clazz){
        InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        ColumnPositionMappingStrategy<T> strategy = new ColumnPositionMappingStrategy<>();
        strategy.setType(clazz);
        CsvToBean<T> csvToBean =
                new CsvToBeanBuilder<T>(reader)
                        .withSkipLines(1)
                        .withMappingStrategy(strategy)
                        .build();
        return csvToBean.parse();
    }


    @SuppressWarnings("unchecked")
    public static <T> List<T> readByColumnName(InputStream inputStream, Class clazz){
        InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        return new CsvToBeanBuilder<T>(reader).withType(clazz).build().parse();
    }
}
